import { ref, onMounted, onBeforeUnmount } from 'vue'

export function lazyLoad (fn) {
  const goods = ref([])
  const target = ref(null)
  const io = new IntersectionObserver(
    function ([{ isIntersecting }]) {
      if (isIntersecting) {
        fn().then(data => {
          goods.value = data.result
        })
      }
      if (!isIntersecting && goods.value.length > 0) {
        target.value && io.unobserve(target.value)
        // console.log(a.b.c);
        io.disconnect()
      }
    },
    {
      threshold: [0]
    }
  )
  onMounted(() => {
    io.observe(target.value)
  })

  onBeforeUnmount(() => {
    io && io.disconnect()
  })

  return { goods, target }
}
